package softwarehouse;

import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

public class De {
    //location and name of the private key to decrpyt the file

    private String privateKeyFile;
    //file to be decrypted
    private String file;

    /**
     * 
     * @param privateKeyFile location and name of the private key to decrypt file
     * @param file to be decrypted
     */
    public De(String privateKeyFile, String file) {
        this.file = file;
        this.privateKeyFile = privateKeyFile;
    }

    /**
     * Decrypt the file and return the contents
     * @return the decrypted text
     */
    public String decrypt() {

        try {
            FileInputStream keyfis = new FileInputStream(privateKeyFile);
            byte[] encKey = new byte[keyfis.available()];
            keyfis.read(encKey);
            System.out.println("Private key length: " + encKey.length);
            keyfis.close();
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privKey = keyFactory.generatePrivate(privateKeySpec);
            FileInputStream sigfis = new FileInputStream(file);
            byte[] sigToVerify = new byte[sigfis.available()];
            sigfis.read(sigToVerify);
            System.out.println("CTFROM FILE: " + sigToVerify.length);
            sigfis.close();

            Cipher cipher = Cipher.getInstance("RSA");
            // System.out.println( "\nStart decryption" );
            cipher.init(Cipher.DECRYPT_MODE, privKey);
            byte[] newPlainText = cipher.doFinal(sigToVerify);
            // System.out.println( "Finish decryption: " );

            String t = new String(newPlainText, "UTF8");
            return t;

        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        };
        return "";
    }
}
